<template>
    <div class="view-wrapper">
        <div class="tabs-body">
            <div class="view-inner-wrap">
                <div class="title">{{ title }}</div>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="攻略标题：" prop="name">
                                <el-input v-model="ruleForm.name" placeholder="请填写" maxlength="60"
                                    show-word-limit></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="标签：" prop="label">
                                <el-radio-group v-model="ruleForm.label">
                                    <el-radio :label="item.id" v-for="(item,index) in labelList" :key="index">{{item.value}}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="路线信息：" required >
                                <div class="content_list_box">
                                    <div class="content_list" v-for="(item, index) in ruleForm.routesList"
                                        :key="index">
                                        <div class="content_item" v-if="item.routesAddress != ''">
                                            <div class="content_l">
                                                <div class="content_text" v-if="index == 0">起</div>
                                                <div class="content_text content_text_three"
                                                    v-else-if="index == (ruleForm.routesList.length - 1) && index > 0">
                                                    终</div>
                                                <div class="content_text content_text_two" v-else-if="index > 0">经</div>
                                            </div>
                                            <div class="content_box" style="width: 100px;">
                                                <el-input class="content_input" placeholder="市县" v-model="item.areaName" :disabled="true"></el-input>
                                            </div>
                                            <div class="content_r" @click="contentRDel(index)" v-if="index != 0">
                                                <img class="content_r_del"
                                                    src="https://kayouyou-1257308601.cos.ap-guangzhou.myqcloud.com/6f5bd532136f49d4b3ac17056e929725.png"
                                                    mode="widthFix"></img>
                                            </div>
                                        </div>
                                        <div class="content_item" v-if="item.routesAddress != ''">
                                            <div class="content_box">
                                                <el-input class="content_input" placeholder="地(店)名(选填)"
                                                    v-model="item.routesName"></el-input>
                                            </div>
                                            <div class="content_r"></div>
                                        </div>
                                        <div class="content_item">
                                            <div class="content_l" v-if="item.routesAddress == ''">
                                                <div class="content_text" v-if="index == 0">起</div>
                                                <div class="content_text content_text_three"
                                                    v-else-if="index == (ruleForm.routesList.length - 1) && index > 0">
                                                    终</div>
                                                <div class="content_text content_text_two" v-else-if="index > 0">经</div>
                                            </div>
                                            <el-form-item :prop="'routesList.' + index + '.routesAddress'"
                                                :rules="rules.routesAddress">
                                                <div class="content_box border_box" @click="mapSiteSelection(index)">
                                                    <div class="content_input ellipseHide">
                                                        <el-input v-model="item.routesAddress"  placeholder="地图选址（必填）" style="pointer-events: none; background-color: #f5f7fa;" ></el-input>
                                                        <!-- <el-input v-model="item.routesAddress" :disabled="true"
                                                            v-show="false"></el-input>
                                                        <span
                                                            v-if="item.routesAddress != ''">{{ item.routesAddress }}</span>
                                                        <span v-else style="color: #999;">地图选址（必填）</span> -->
                                                    </div>
                                                </div>
                                            </el-form-item>

                                            <div class="content_r" @click="contentRDel(index)" v-if="index != 0">
                                                <img class="content_r_del"
                                                    src="https://kayouyou-1257308601.cos.ap-guangzhou.myqcloud.com/6f5bd532136f49d4b3ac17056e929725.png"
                                                    mode="widthFix"></img>
                                            </div>
                                        </div>
                                        <div class="content_switch" v-if="index != (ruleForm.routesList.length - 1)">
                                            <div class="content_switch_line"></div>
                                            <div class="content_switch_move" @click="switchChange(index)">
                                                <img src="https://kayouyou-1257308601.cos.ap-guangzhou.myqcloud.com/ed53ed5edec14bdf8b59077f1f6c67c4.png"
                                                    mode="widthFix"></img>
                                            </div>
                                            <div class="content_switch_line"></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="content_add" @click="contentAdd">
                                    <p>+</p>
                                    <p class="content_add_word">新增</p>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="缩略图：" prop="thumbnail">
                                <el-checkbox-group v-model="ruleForm.thumbnail" v-show="false"></el-checkbox-group>
                                <ImageUploadMoreOldUrl :limit="1" :fileSize="6" v-model="ruleForm.thumbnail"
                                    :fileType='["bmp", "png", "jpg", "jpeg", "gif"]'> </ImageUploadMoreOldUrl>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="攻略内容：" prop="details">
                                <WangEditor :value.sync="ruleForm.details" style="width:900px;"></WangEditor>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item>
                        <el-button type="primary" @click="cancelForm">取消</el-button>
                        <el-button type="primary" @click="saveDraft" :loading="loading">存草稿</el-button>
                        <el-button type="primary" @click="preview">预览</el-button>
                        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">确认发布</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <el-dialog title="选择定位" :visible.sync="modelMsg" :close-on-click-modal="false">
            <div class="msgDiv">
                <el-autocomplete style="width: 80%; margin-right: 10px" class="inline-input" v-model="address"
                    :fetch-suggestions="watchInput" placeholder="请输入内容" :trigger-on-focus="false"
                    @select="handleSelect">
                </el-autocomplete>
                <div id="container" style="margin-top: 20px"></div>
                <div class="dialog_bottom">
                    <el-button style="margin-right: 60px" @click="modelMsg = false">取消</el-button>
                    <el-button type="primary" @click="determine">确定</el-button>
                </div>
            </div>
        </el-dialog>
        <LookDiglog v-if="lookStatus" :ruleForm="ruleForm" :visible.sync="lookStatus" @success="_handleSuccess"></LookDiglog>
    </div>
</template>

<script>
import {
    douyinVideoTalentWorksAdd,
    douyinVideoTalentWorksDetail,
    douyinVideoTalentWorksEdit,
    douyinVideoTalentWorksAreaName
  } from "@/api/incentiveManagement/strategyManagement";
import { cancelFormTab } from '@/utils/common'
import ImageUploadMoreOldUrl from "@/components/ImageUploadMoreOldUrl"
import WangEditor from '@/components/WangEditor'
import LookDiglog from './components/lookDiglog'
export default {
    name: "",
    components: {
        LookDiglog,
        ImageUploadMoreOldUrl,
        WangEditor,
    },
    data() {
        return {
            title: '新增攻略',
            pathType: 'add',
            id:'',//编辑id
            labelList:[],//标签列表
            loading: false,
            lookStatus: false,
            ruleForm: {
                name: '', //攻略标题
                label: '1', //标签
                thumbnail: '', //缩略图 
                //路线信息
                routesList: [{
                    areaName: '',
                    areaCode: '',
                    routesAddress: '',
                    routesName: '',
                    lat: '',
                    lng: '',
                },
                ],
                details: '',//攻略内容
            },
            address: '',//选择地图
            contenIndex: 0, //下标
            modelMsg: false, //显示模态框
            address: "", //输入的地址
            mapList: [], //用来存搜索到的所有地址
            mapVal: "", //创建的地图，赋值用
            lng:'',//经度
            lat:'',//纬度
            rules: {
                name: [{
                    required: true,
                    message: '请填写攻略标题',
                    trigger: ['blur', 'change']
                },],
                label: [{
                    required: true,
                    message: '请选择标签',
                    trigger: ['blur', 'change']
                }],
                routeInformationList: [{
                    required: true,
                    message: '请选择路线信息',
                    trigger: ['blur', 'change']
                },],

                thumbnail: [{
                    required: true,
                    message: '请上传图片',
                    trigger: 'change'
                },],
                details: [{
                    required: true,
                    message: '请填写攻略内容',
                    trigger: ['blur', 'change']
                },],
                routesAddress: [{
                    required: true,
                    message: '请选择地址信息',
                    trigger: ['blur', 'change']
                },],

            },
        };
    },
    created() {
        this.getDict()
        this.pathType = this.$route.query.pathType
        if (this.pathType == 'edit') {
            this.id = this.$route.query.id
            this.title = '编辑攻略'
            this.getDetail()
        } else if(this.pathType == 'add'){
            this.title = '新增攻略'
        }
    },
    watch: {
        //监听模态框是否显示,显示就执行初始化地图方法
        // modelMsg(newVal, oldVal) {
        //     console.log(newVal);
        //     if (newVal == true) {
        //         this.initMap(20.049818248, 110.354108124);
        //     }
        // },
    },
    methods: {
         // 根据字典值获取信息
         getDict() {
            var dictType = "douyin_video_talent_works_label";
            this.$getSelectList(dictType)
                .then((res) => {
                    this.labelList = res.result[0].dictList;
                
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        //获取详情
        getDetail() {
            douyinVideoTalentWorksDetail(this.id).then(response => {
                this.ruleForm = response.result
                if(this.ruleForm.routesList == ''){
                    var routesList =  [{
                        areaName: '',
                        areaCode: '',
                        routesAddress: '',
                        routesName: '',
                        lat: '',
                        lng: '',
                       },
                    ]
                    this.ruleForm.routesList = routesList
                }
            });
        },
        //成功操作 
        _handleSuccess() {
            // this.getList();
        },
        // 预览
        preview() {
            console.log('this.ruleForm',this.ruleForm)
            this.lookStatus = true
        },
        //删除
        handleDelete(index) {
            // this.ruleForm.materialsDTOList.splice(index, 1) //materialsDTOList和seleMaterialsDTOListId已经在获取信息中双向绑定,故这里不需要删除方法,这边也写删除方法会有问题
            this.ruleForm.seleMaterialsDTOListId.splice(index, 1)
        },
        // 取消
        cancelForm() {
            // this.$router.go(-1)
            cancelFormTab('/incentiveManagement/strategyManagement') //关闭当前标签页
        },
        // 存草稿
        saveDraft() {
            if(this.ruleForm.name == ''){
                this.$message.error('请填写攻略标题')
                return false
            }
            var data = {
                 ...this.ruleForm
             }
             var routesList = []
             data.routesList.forEach(vo=>{
                if(vo.routesAddress != ''){
                    routesList.push(vo)
                }
             })
             data.routesList = routesList
             data.status = 3
             this.loading = true
             if (this.pathType == 'add') {
                    this.addData(data,'添加成功')
                } else if (this.pathType == 'edit') {
                    this.editData(data)
                }
        },
        // 
        submitForm(formName) {
            console.log('data', this.ruleForm)
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.loading = true
                    var data = {
                        ...this.ruleForm
                    }
                    data.status = 2
                    if (this.pathType == 'add') {
                        this.addData(data,'已发布')
                    } else if (this.pathType == 'edit') {
                        this.editData(data)
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 新增数据
        addData(data,msg) {
            console.log('data', data)
            douyinVideoTalentWorksAdd(data).then(res => {
                this.$message.success(msg)
                setTimeout(() => {
                    this.loading = false
                    cancelFormTab('/incentiveManagement/strategyManagement') //关闭当前标签页
                }, 1000);
            }).catch(() => {
                this.loading = false
            })
        },
        // 编辑数据
        editData(data) {
            douyinVideoTalentWorksEdit(data).then(res => {
                this.$message.success('修改成功')
                setTimeout(() => {
                    this.loading = false
                    cancelFormTab('/incentiveManagement/strategyManagement') //关闭当前标签页
                }, 1500);
            }).catch(() => {
                this.loading = false
            })
        },
        // 地址选择
        mapSiteSelection(index) {
            this.modelMsg = true
            this.contenIndex = index
            if(this.ruleForm.routesList[this.contenIndex].routesAddress != ''){
              this.address = this.ruleForm.routesList[this.contenIndex].routesName+'-'+this.ruleForm.routesList[this.contenIndex].routesAddress
              this.initMap(this.ruleForm.routesList[this.contenIndex].lat, this.ruleForm.routesList[this.contenIndex].lng);
            //   this.address = this.ruleForm.routesList[this.contenIndex].routesName+'-'+this.ruleForm.routesList[this.contenIndex].routesAddress
            }else{
                this.initMap(20.049818248, 110.354108124);
                this.address = ''
            }
            
        },
        // 新增列表
        contentAdd(e) {
            var obj = {
                areaName: '',
                routesAddress: '',
                routesName: '',
                lat: '',
                lng: '',
            }
            if (this.ruleForm.routesList.length < 20) {
                this.ruleForm.routesList.push(obj)
            } else {
                this.$message.error('最多可设置二十条位置信息')
            }
        },
        // 删除足迹
        contentRDel(index) {
            this.ruleForm.routesList.splice(index, 1)
        },
        // 切换
        switchChange(index) {
            var routesList = this.ruleForm.routesList;
            var oneInfo = routesList[index]
            // routesList[index] = routesList[index + 1]
            // routesList[index + 1] = oneInfo
            this.$set(this.ruleForm.routesList, index, routesList[index + 1])
            this.$set(this.ruleForm.routesList, index + 1, oneInfo)
        },
        // 选择地图地址
        handleSelect(item) {
            // console.log('item22222',item);
            this.initMap(item.location.lat, item.location.lng);
            this.address = item.value;
            this.lng = item.location.lng;
            this.lat = item.location.lat;
        },
        determine() {
            // console.log(this.address);
            if(this.address == ''){
                this.$message.error('请选择地址信息')
            }else{
                this.getCityProper(this.lat,this.lng)
                this.modelMsg = false;
            }

        },
        // 根据地址 获取省市区
        getCityProper(lat,lng,){
            var location = lat+','+lng
            this.reverseAddressResolution(location,res=>{
                var adcode = res.ad_info.adcode
                douyinVideoTalentWorksAreaName(adcode).then(vo=>{
                    if(vo.result == ''){
                        this.$message.error('请选择海南省地址')
                    }else{
                        this.ruleForm.routesList[this.contenIndex].areaName = vo.result.name;
                        this.ruleForm.routesList[this.contenIndex].areaCode = vo.result.code;
                        var nameCode = this.address.split('-')
                        this.ruleForm.routesList[this.contenIndex].routesName = nameCode[0];
                        this.ruleForm.routesList[this.contenIndex].routesAddress = nameCode[1];
                        this.ruleForm.routesList[this.contenIndex].lng = this.lng;
                        this.ruleForm.routesList[this.contenIndex].lat = this.lat;
                    }

                })
           })
        },
        // 搜索接口
        watchInput(queryString, cb) {
            console.log(queryString);
            const KEY = "IFRBZ-GZ2CQ-YHW5J-GSUGE-RC7VS-JBBWN";
            let url = "https://apis.map.qq.com/ws/place/v1/suggestion";
            let keyword = queryString; //传入的关键词
            this.$jsonp(url, {
                key: KEY,
                region_fix:1,
                region: "海南",
                keyword: keyword,
                output: "jsonp",
            })
            .then((res) => {
                let opt = [];
                res.data.forEach((res) => {
                    let opt1 = {
                        value: res.title + "-" + res.address,
                        location: res.location,
                    };
                    opt.push(opt1);
                });
                this.mapList = opt;
                console.log(this.mapList);
                // 调用 callback 返回建议列表的数据
                cb(this.mapList);
            })
            .catch((err) => {
                console.log(err);
            });
        },
        initMap(lat, lng) {
            //如果地图存在，就销毁，下面会重新创建一个
            if (this.mapVal) {
                this.mapVal.destroy();
            }
            //定义地图中心点坐标
            //this.$nextTick是等Dom加载完再执行
            this.$nextTick(() => {
                var center = new window.TMap.LatLng(lat, lng);
                //定义map变量，调用 TMap.Map() 构造函数创建地图
                this.mapVal = new TMap.Map(document.getElementById("container"), {
                    center: center, //设置地图中心点坐标
                    zoom: 17.2, //设置地图缩放级别
                    pitch: 43.5, //设置俯仰角
                    rotation: 45, //设置地图旋转角度
                    viewMode: "2D",
                    mapStyleId: "style1", //个性化样式
                });
                //初始化marker
                var marker = new TMap.MultiMarker({
                    id: "marker-layer", //图层id
                    map: this.mapVal,
                    styles: {
                        //点标注的相关样式
                        marker: new TMap.MarkerStyle({
                            width: 25,
                            height: 35,
                            anchor: {
                                x: 16,
                                y: 32,
                            },
                            src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png",
                        }),
                    },
                    geometries: [{
                        //点标注数据数组
                        id: "demo",
                        styleId: "marker",
                        position: new TMap.LatLng(lat, lng),
                        properties: {
                            title: "marker",
                        },
                    },],
                });
            });
        },
        // 逆地址解析(坐标位置描述)
        reverseAddressResolution(location, cb) {
            // console.log(queryString);
            const KEY = "IFRBZ-GZ2CQ-YHW5J-GSUGE-RC7VS-JBBWN";
            let url = "https://apis.map.qq.com/ws/geocoder/v1";
            this.$jsonp(url, {
                key: KEY,
                location:location,
                output: "jsonp",
            })
            .then((res) => {
                // 调用 callback 返回建议列表的数据
                cb(res.result);
            })
            .catch((err) => {
                console.log(err);
            });
        },
    },
};

</script>

<style lang="scss" scoped>
.tabs-body {
    background-color: #fff;
    padding: 20px 0;
}

.title {
    font-size: 24px;
    padding: 14px 30px 14px 14px;
    margin-bottom: 14px;
    color: #222;
    font-weight: bold;
    border-bottom: 1px solid #DCDFE6;
}

.seleInp .el-select {
    width: 100%;
}
.el-input__suffix{
    right: -50px;
}
.rowList {
    display: flex;
    justify-content: flex-start;

    .el-select {
        width: 130px;
    }
}

.inpBox {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .el-input {
        width: 100px;
    }
}

.btnBox {
    width: 100px;
    margin-left: 20px;
}

.mar-r-10 {
    margin-right: 14px;

}

.txt {
    font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
    font-weight: 700;
    color: #606266;

}

.mar-l-10 {
    margin-left: 14px;
}

.disSb {
    display: flex;
    justify-content: space-between;
}

.ellipseHide {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    word-wrap: break-word;
}

.dialog_bottom {
    margin-top: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
}

.content_list_box {
    margin-bottom: 20px;
}

.content_list {
    margin-bottom: 30px;
    position: relative;
    display: flex;
    flex-direction: row;
}

.content_item {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-right: 10px;
    // margin-bottom: 8px;
}

.content_item:last-child,
.content_list:last-child {
    margin-bottom: unset;
}

.content_l {
    width: 41px;
    height: 33px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
}

.content_text {
    width: 25px;
    height: 25px;
    color: #45D180;
    font-size: 12px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    background: #D7FFDB;
    border-radius: 50%;
}

.content_text_two {
    color: #FF524E;
    background: #FFEEEE;
}

.content_text_three {
    color: #7B7B7B;
    background: #F1F1F1;
}

.content_box {
    width: 350px;
    height: 36px;
    border-radius: 4px;
    display: flex;
    flex-direction: row;
    align-items: center;
    color: #222222;
    font-size: 12px;
    box-sizing: border-box;
    cursor: pointer;
}

.border_box {
    // border: 1px solid #DCDFE6;
}

.content_box .content_box_img {
    width: 12px;
    height: 9px;
}

.content_input {
    flex: 1;
    width: 0;

    span {
        padding: 0 15px;
        box-sizing: border-box;
    }

    .el-input {
        width: 100%;
    }
}

.content_input_placeholder {
    color: #cccccc;
    font-size: 12px;
}

.content_r {
    flex: 1;
    width: 0;
    display: flex;
}

.content_r_del {
    width: 20px;
    height: 20px;
    margin-left: 10px;
}

.content_box_right {
    width: 9px;
    height: 9px;
}

.content_add {
    border: 1px solid #305DFF;
    color: #305DFF;
    width: 56px;
    height: 32px;
    font-size: 12px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 40px;
}

.content_add_word {
    margin-left: 6px;
}

.content_switch_move {
    padding: 7px 0;
}

.content_switch {
    position: absolute;
    top: 30px;
    left: 10px;
    height: calc(100% - 15px);
    display: flex;
    flex-direction: column;
    align-items: center;
}

.content_switch_line {
    flex: 1;
    border-left: 1px dashed #DFDFDF;
}

.content_switch_move img {
    width: 18px;
    height: 18px;
}
</style>